package org.example.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.erp.controller.DataResult;
import org.example.erp.domain.*;
import org.example.erp.enums.OrderStatusEnum;
import org.example.erp.service.*;
import org.example.erp.mapper.NewSalesOrderMapper;
import org.example.erp.utils.UtilMethod;
import org.example.erp.web.VO.SalesOrderVO;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 28254
 * @description 针对表【new_sales_order(销售订单表)】的数据库操作Service实现
 * @createDate 2024-12-02 14:11:06
 */
@Service
@RequiredArgsConstructor
public class NewSalesOrderServiceImpl extends ServiceImpl<NewSalesOrderMapper, NewSalesOrder>
        implements NewSalesOrderService {

    private final NewSalesOrderItemService newSalesOrderItemService;
    private final ProductBomService productBomService;
    private final ProWorkorderService proWorkorderService;
    private final ProWorkorderBomService proWorkorderBomService;
    private final UnitsService unitsService;

    // 新增订单数据
    @Override
    public void insertPrimaryOrder(NewSalesOrder newSalesOrder) {
        newSalesOrder.setSalesOrderCode(UtilMethod.getRndomString("PO")); //自动生成主订单编码
        newSalesOrder.setStatus(OrderStatusEnum.PREPARE); //默认状态为草稿
        this.save(newSalesOrder);
        List<NewSalesOrderItem> items = newSalesOrder.getSalesOrderItems();
        if (items.isEmpty()) return;
        //给新添加的子菜单设置主订单id和子订单编码
        items.forEach(item -> {
            item.setSalesOrderId(newSalesOrder.getSalesOrderId());
            item.setSalesOrderItemCode(UtilMethod.getRndomString("POI"));
        });
        // 批量新增
        newSalesOrderItemService.saveBatch(items);
    }

    // 更新主订单数据,主订单和子订单都需携带主键ID
    @Override
    public void updatePrimaryOrder(NewSalesOrder newSalesOrder) {
        this.updateById(newSalesOrder);
        List<NewSalesOrderItem> items = newSalesOrder.getSalesOrderItems();
        if (items != null) {
            if (newSalesOrder.getStatus() == OrderStatusEnum.CONFIRMED) {
                handleOrderItem(items); //新增工单信息
            }

            List<NewSalesOrderItem> existsItems = new ArrayList<>();
            List<NewSalesOrderItem> noExistsItems = new ArrayList<>();
            for (NewSalesOrderItem item : items) {
                if (item.getSalesOrderItemId() != null) {
                    existsItems.add(item);
                } else {
                    item.setSalesOrderId(newSalesOrder.getSalesOrderId());
                    item.setSalesOrderItemCode(UtilMethod.getRndomString("POI"));
                    noExistsItems.add(item);
                }
            }
            newSalesOrderItemService.updateBatchById(existsItems); // 批量修改已有的子订单
            newSalesOrderItemService.saveBatch(noExistsItems); //批量新增没有的子订单
        }
    }

    //删除主订单数据，如果存在子订单数据，则不允许删除
    @Override
    public DataResult deletePrimaryOrders(List<Integer> salesOrderIds) {
        QueryWrapper<NewSalesOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("sales_order_id", salesOrderIds);
        if (newSalesOrderItemService.count(queryWrapper) > 0) {
            return new DataResult(500, null, "存在关联子订单，不允许删除", Instant.now().toEpochMilli());
        }
        this.removeByIds(salesOrderIds);
        return DataResult.success();
    }

    // 分页查询
    @Override
    public IPage<SalesOrderVO> findSalesOrders(Integer pageNum, Integer pageSize, String salesOrderCode, String salesOrderName) {
        Page<SalesOrderVO> page = new Page<>(pageNum, pageSize);
        return baseMapper.findSalesOrders(page, salesOrderCode, salesOrderName);
    }

    //查询主订单详情
    @Override
    public NewSalesOrder findSalesOrderById(Integer salesOrderId) {
        NewSalesOrder newSalesOrder = baseMapper.findSalesOrderById(salesOrderId);
        List<NewSalesOrderItem> list = newSalesOrder.getSalesOrderItems().stream().filter(item -> item.getSalesOrderItemId() != null).toList();
        newSalesOrder.setSalesOrderItems(list);
        return  newSalesOrder;
    }


    private List<NewSalesOrderItem> handleOrderItem(List<NewSalesOrderItem> items) {
        List<ProWorkorder> proWorkorderList = new ArrayList<>();
        for (NewSalesOrderItem item : items) {
            ProWorkorder proWorkorder = new ProWorkorder();
            proWorkorder.setProductId(item.getProductId()); //产品id
            proWorkorder.setProductCode(item.getProductCode()); //产品编码
            proWorkorder.setProductName(item.getProductName()); //产品名称
            proWorkorder.setWorkorderCode(UtilMethod.getRndomString("GD")); //工单编码
            proWorkorder.setWorkorderName(item.getProductName()); //工单名称
            proWorkorder.setStatus("PREPARE"); //工单状态
            proWorkorder.setQuantity(item.getSalesOrderQuantity()); //数量
            proWorkorderList.add(proWorkorder);
        }
        proWorkorderService.saveBatch(proWorkorderList);
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).getProductId().equals(proWorkorderList.get(i).getProductId())) {
                items.get(i).setWorkorderId(proWorkorderList.get(i).getWorkorderId());
            }
        }

        //=======//
        for (int i = 0; i < proWorkorderList.size(); i++) {
            List<ProductBom> byId = productBomService.findById(proWorkorderList.get(i).getProductId());
            if (byId != null) {
                for (ProductBom p : byId) {
                    QueryWrapper<Units> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(Units::getUnitName, p.getBomUnit());
                    Units list = unitsService.getOne(queryWrapper);
                    ProWorkorderBom proWorkorderBom = new ProWorkorderBom();
                    proWorkorderBom.setItemId(p.getBomMaterialId());
                    proWorkorderBom.setItemCode(p.getBomMaterialCode());
                    proWorkorderBom.setItemName(p.getBomMaterialName());
                    proWorkorderBom.setItemSpc(p.getBomMaterialSpec());
                    proWorkorderBom.setUnitOfMeasure(list.getUnitName());
                    proWorkorderBom.setItemOrProduct(p.getBomMaterial());
                    Integer o = proWorkorderList.get(i).getQuantity() * p.getQuantity();
                    proWorkorderBom.setQuantity(o);
                    proWorkorderBom.setWorkorderId(proWorkorderList.get(i).getWorkorderId());
                    boolean s = proWorkorderBomService.save(proWorkorderBom);
                }
            }
        }


        return items;
    }


}




